package com.chixing.service.impl;


import com.chixing.controller.WebSocketProcess;
import com.chixing.entity.Comment;
import com.chixing.entity.Movie;
import com.chixing.repository.CommentDocRepository;
import com.chixing.repository.CommentRepository;
import com.chixing.service.CommentService;
import com.chixing.service.IMovieService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liwenjing
 * @since 2025-10-07
 */
@RequiredArgsConstructor
@Service
public class CommentServiceImpl implements CommentService {

    private final CommentRepository repository;
    @Autowired
    private IMovieService movieService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /*@Autowired
    public CommentServiceImpl(CommentRepository repository) {
        this.repository = repository;
    }*/
    public Comment postComment(Comment comment) {
// parentId 为 null 表示顶层评论
        comment.setCreateTime(System.currentTimeMillis());
        //  根据 movieId 查询电影名并写入
        if (comment.getMovieId() != null) {
            try {
                // 添加详细日志
                System.out.println("查询电影信息，movieId: " + comment.getMovieId());

                Movie movie = movieService.getById(comment.getMovieId());

                if (movie != null) {
                    String movieName = movie.getMovieName();
                    System.out.println("查询到的电影名称: " + movieName);
                    comment.setMovieName(movieName);
                } else {
                    System.out.println("警告：未找到对应的电影，movieId: " + comment.getMovieId());
                    comment.setMovieName("未知电影");
                }
            } catch (Exception e) {
                System.err.println("查询电影信息异常: " + e.getMessage());
                comment.setMovieName("查询失败");
            }
        } else {
            System.out.println("警告：comment 的 movieId 为 null");
        }

        return repository.save(comment);
    }


    @Override
    public Comment reply(String parentId, Comment reply) {
// 设置父评论、movieId 继承父评论的 movieId（保证一致性）
        Optional<Comment> parent = repository.findById(parentId);
        if (!parent.isPresent()) {
            throw new IllegalArgumentException("父评论不存在: " + parentId);
        }
        Comment parentComment = parent.get();
        reply.setParentId(parentId);
        reply.setMovieId(parent.get().getMovieId());
        reply.setCreateTime(System.currentTimeMillis());

        //  movieName
        String movieName = movieService.getById(reply.getMovieId()).getMovieName();
        reply.setMovieName(movieName);
        System.out.println(movieName + "==============");

        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());

        // ✅ 推送消息给被回复的人
        Map<String, String> msg = new HashMap<>();
        msg.put("type", "reply");
        msg.put("movieName", movieName);
        msg.put("movieId", reply.getMovieId());
        msg.put("content", reply.getContent());
        msg.put("fromUserId", reply.getUserId());
        msg.put("toUserId", parentComment.getUserId());
        msg.put("status", String.valueOf(0));


        // 发送到RabbitMQ（使用wsExchange和对应的routingKey）
        try {
            rabbitTemplate.convertAndSend("wsExchange", "key1", msg);
        } catch (Exception e) {
            System.out.println("评论回复消息发送MQ失败");
            throw new RuntimeException("消息推送失败");
        }

        return repository.save(reply);

    }


    @Override
    public void like(String commentId) {
// 简单实现：读取-修改-保存（可改为原子操作或使用 $inc）
        repository.findById(commentId).ifPresent(c -> {
            c.setLikes(c.getLikes() + 1);
            repository.save(c);
        });
    }


    @Override
    public List<Comment> getCommentsTreeByMovieId(String movieId) {
// 读取该电影的所有评论，然后在内存中组装成树。
        List<Comment> all = repository.findByMovieIdOrderByCreateTimeAsc(movieId);
        Map<String, Comment> map = new LinkedHashMap<>();
        List<Comment> roots = new ArrayList<>();


// 建立 id -> comment 映射（浅拷贝 children 清空）
        for (Comment c : all) {
            c.setChildren(new ArrayList<>());
            map.put(c.getId(), c);
        }


// 将每个评论挂到父节点或根集合
        for (Comment c : all) {
            if (c.getParentId() == null || c.getParentId().trim().isEmpty()) {
                roots.add(c);
            } else {
                Comment parent = map.get(c.getParentId());
                if (parent != null) {
                    parent.getChildren().add(c);
                } else {
// 如果找不到父节点（可能被删除），就当作根节点处理
                    roots.add(c);
                }
            }
        }


        return roots;
    }


    @Override
    public List<Comment> getCommentsByUserId(String userId) {

        return repository.findByUserIdOrderByCreateTimeDesc(userId);
    }




    @Autowired
    private WebSocketProcess webSocketProcess;

}